package com.rzgeo.workmap;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.amap.api.maps.CameraUpdate;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.CameraPosition;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.maps.model.PolygonOptions;
import com.esri.arcgisruntime.geometry.Envelope;
import com.esri.arcgisruntime.geometry.Geometry;
import com.esri.arcgisruntime.geometry.GeometryEngine;
import com.rzgeo.rzmaplib.model.RmlAppMainDir;
import com.rzgeo.rzmaplib.model.RmlEnv;
import com.rzgeo.rzmaplib.model.RmlPrj;
import com.rzgeo.rzmaplib.query.IQuery;
import com.rzgeo.rzmaplib.util.IRmlSerializable;
import com.rzgeo.rzmaplib.util.RmlUtil;

public class CatalogActv extends AppCompatActivity {

    MapView _mapView = null;
    private ListView _prjList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.actv_catalog);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        //获取地图控件引用
        _mapView = findViewById(R.id.mapView);
        //在activity执行onCreate时执行mMapView.onCreate(savedInstanceState)，创建地图
        _mapView.onCreate(savedInstanceState);

        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(10000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        _mapView.getMap().setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
        _mapView.getMap().getUiSettings().setMyLocationButtonEnabled(true);//设置默认定位按钮是否显示，非必需设置。
        _mapView.getMap().getUiSettings().setCompassEnabled(true);
        _mapView.getMap().getUiSettings().setScaleControlsEnabled(true);

        _mapView.getMap().setMyLocationEnabled(true);// 设置为true表示启动显示定位蓝点，false表示隐藏定位蓝点并不进行定位，默认是false。

        FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
        RmlAppMainDir appDir = RmlEnv.getInstance().getAppDir();

        _prjList=findViewById(R.id.lv_prjs);
        _prjList.setAdapter(
                new PrjAdapter(
                        this, appDir.prjsSet.getPrjs()));

    }

    public static class StartInfo implements IRmlSerializable {
        public String userName;

        public StartInfo(String userName) {
            this.userName = userName;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.actv_catalog, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，销毁地图
        _mapView.onDestroy();
    }
    @Override
    protected void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView.onResume ()，重新绘制加载地图
        _mapView.onResume();
    }
    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        _mapView.onPause();
    }
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        _mapView.onSaveInstanceState(outState);
    }

    public class PrjAdapter extends BaseAdapter{

        private final RmlPrj[] _prjs;
        private final LayoutInflater _inflater;

        public PrjAdapter(Context context, RmlPrj[] prjs){
            _prjs=prjs;
            _inflater= LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return _prjs.length;
        }

        @Override
        public Object getItem(int position) {
            return _prjs[position];
        }

        @Override
        public long getItemId(int position) {
            return _prjs[position].getUID();
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            PrjViewHolder holder;
            if (convertView == null) {
                convertView = _inflater.inflate(R.layout.content_catalog_actv_item, null);
                holder = new PrjViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (PrjViewHolder) convertView.getTag();
            }

            holder.setData(_prjs[position],position);
            return convertView;
        }

        public class PrjViewHolder{

            private final TextView txvTitle;
            private final TextView txvState;
            private final TextView txvInvestigator;
            private final TextView txvBasemapMaker;
            private final TextView txvCreateTim;
            private final TextView txvEditTim;
            private final TextView txvRemark;
            private final TextView btnDelete;
            private final View btnLocate;
            private final View btnOpen2d;
            private final View btnOpen3d;
            private final View btnOpenDrone;
            private RmlPrj _prj;
            private int _position;

            public PrjViewHolder(View cv) {
                txvTitle=cv.findViewById(R.id.txv_title);
                txvState=cv.findViewById(R.id.txv_state);
                txvInvestigator=cv.findViewById(R.id.txv_investigator);
                txvBasemapMaker=cv.findViewById(R.id.txv_basemap_maker);
                txvCreateTim=cv.findViewById(R.id.txv_create_tim);
                txvEditTim=cv.findViewById(R.id.txv_edit_tim);
                txvRemark=cv.findViewById(R.id.txv_remark);


                btnDelete=cv.findViewById(R.id.btn_delete);
                btnLocate=cv.findViewById(R.id.btn_locate);
                btnOpen2d=cv.findViewById(R.id.btn_open2d);
                btnOpen3d=cv.findViewById(R.id.btn_open3d);
                btnOpenDrone=cv.findViewById(R.id.btn_opendrone);
                btnDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        RmlUtil.Tip.Toast("暂不支持删除");
                    }
                });
                btnLocate.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        try{
                            _prj.getExtent(new IQuery.IOnQueryGeometry() {
                                @Override
                                public void onGeomtry(Geometry geometry) {
                                    try {
                                        _mapView.getMap().clear();
                                        com.esri.arcgisruntime.geometry.Envelope ext = (Envelope) geometry;
                                        ext = (Envelope) GeometryEngine.project(ext, RmlUtil.SR.getGeoSR());

                                        CameraPosition cameraPosition = new CameraPosition(new LatLng(ext.getCenter().getY(), ext.getCenter().getX()), 11, 0, 0);
                                        CameraUpdate mCameraUpdate = CameraUpdateFactory.newCameraPosition(cameraPosition);
                                        _mapView.getMap().animateCamera(mCameraUpdate, 2, null);

                                        PolygonOptions pop = new PolygonOptions();

                                        pop.add(new LatLng(
                                                ext.getYMin(), ext.getXMin()));
                                        pop.add(new LatLng(
                                                ext.getYMax(), ext.getXMin()));
                                        pop.add(new LatLng(
                                                ext.getYMax(), ext.getXMax()));
                                        pop.add(new LatLng(
                                                ext.getYMin(), ext.getXMax()));

                                        pop.fillColor(R.color.prj_fill)
                                                .strokeColor(Color.RED).strokeWidth(1);
                                        _mapView.getMap().addPolygon(pop);
                                    }catch (Exception e){
                                        RmlUtil.Log.Err(e);
                                    }
                                }

                                @Override
                                public void onFailed(String msg) {
                                    RmlUtil.Log.Err(msg);
                                }
                            });

                        }catch (Exception e){
                            RmlUtil.Log.Err(e);
                        }
                    }
                });
                btnOpen2d.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(_prj.checkData(CatalogActv.this)){
                            MapActv.StartInfo startInfo=new MapActv.StartInfo(_prj.getName());
                            Intent intent=new Intent();
                            intent.putExtra(StartInfo.Key,startInfo);
                            intent.setClass(CatalogActv.this,MapActv.class);
                            startActivity(intent);
                        }
                    }
                });

                btnOpen3d.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(_prj.checkData(CatalogActv.this)) {
                            SceneActv.StartInfo startInfo = new SceneActv.StartInfo(_prj.getName());
                            Intent intent = new Intent();
                            intent.putExtra(StartInfo.Key, startInfo);
                            intent.setClass(CatalogActv.this, SceneActv.class);
                            startActivity(intent);
                        }
                    }
                });

                btnOpenDrone.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(_prj.checkData(CatalogActv.this)) {
                            DroneMapActv.StartInfo startInfo = new DroneMapActv.StartInfo(_prj.getName());
                            Intent intent = new Intent();
                            intent.putExtra(StartInfo.Key, startInfo);
                            intent.setClass(CatalogActv.this, DroneMapActv.class);
                            startActivity(intent);
                        }
                    }
                });
            }

            public void setData(RmlPrj prj, int position) {
                _prj=prj;
                _position=position;

                txvTitle.setText(prj.getName());
                txvState.setText(prj.getState().toString());
                txvInvestigator.setText(prj.getInvestigator());
                txvBasemapMaker.setText(prj.getBasemapMaker());
                txvCreateTim.setText(prj.getCreateTim());
                txvEditTim.setText(prj.getEditTim());
                txvRemark.setText(prj.getRemark());
            }
        }
    }
}
